package com.tempo.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * create by tempo on 2015\11\14
 * 可以设置宽高比
 */
public class RatioLayout extends FrameLayout{
	/**
	 * 宽高比
	 */
	private float ratio=1;
	public RatioLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
//		ratio=attrs.getAttributeFloatValue(R.styleable.RatioLayout_ratio,ratio);
		TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.RatioLayout);
		ratio =typedArray.getFloat(R.styleable.RatioLayout_ratio,ratio);
	}

	public RatioLayout(Context context, AttributeSet attrs) {
		this(context, attrs,0);
	}

	public RatioLayout(Context context) {
		this(context, null);
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int width=MeasureSpec.getSize(widthMeasureSpec);
		int widthMode=MeasureSpec.getMode(widthMeasureSpec);
		int height=MeasureSpec.getSize(heightMeasureSpec);
		int heightMode=MeasureSpec.getMode(heightMeasureSpec);
		
		int aWidthSpec=widthMeasureSpec;
		int aHeightSpec=heightMeasureSpec;
		if(widthMode==MeasureSpec.EXACTLY&&heightMode!=MeasureSpec.EXACTLY){
			height=(int) (width/ratio+0.5);
			aHeightSpec=MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
			
		}else if(widthMode!=MeasureSpec.EXACTLY&&heightMode==MeasureSpec.EXACTLY){
			width=(int) (height*ratio+0.5);
			aWidthSpec=MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
		}
		super.onMeasure(aWidthSpec,aHeightSpec);
	}

}
